﻿#include"XQSystemTray.h"
#include"XQEventFilterObject.h"
#include"XQLog.hpp"
#include<QApplication>
#include<QStyle>
#include<QMenu>
XQSystemTray::XQSystemTray(const QIcon& icon, QObject* parent)
	:QSystemTrayIcon(icon,parent)
{
	init();
}

XQSystemTray::XQSystemTray(QObject* parent)
	:QSystemTrayIcon(parent)
{
	setIcon(QApplication::style()->standardIcon(QStyle::SP_DesktopIcon));
	init();
}

XQSystemTray::~XQSystemTray()
{
	if (contextMenu() != nullptr)
		contextMenu()->deleteLater();
	hide();
}


void XQSystemTray::setContextMenu()
{
	QMenu* menu = new QMenu();
	menuAddQuit(menu);
	QSystemTrayIcon::setContextMenu(menu);
}

QAction* XQSystemTray::menuAddShowHideWindow(QMenu* menu, QWidget* receive, const QString& showText, const QString& hideText)
{
	if (menu == nullptr)
		return nullptr;
	return menu->addAction("显示/隐藏"/*receive->isVisible()||receive->isMinimized() ? showText : hideText*/, [=] {
		if(!receive->isVisible()||receive->isMinimized())
		{//当前是隐藏或最小化状态
			if(receive->isMinimized())
				//receive->setWindowState(Qt::WindowNoState);
				receive->showNormal();
			if(!receive->isVisible())
				receive->setVisible(true);
			receive->activateWindow();
		}
		else
		{//当前是显示状态
			receive->setVisible(false);
		}
		/*auto list=contextMenu()->actions();
		for (auto& action:list)
		{
			auto text=(receive->isVisible() ? showText : hideText);
			if (action->text() == text)
			{
				action->setText(receive->isVisible() || receive->isMinimized() ?hideText: showText);
				break;
			}
		}*/
		});
	/*receive->installEventFilter(new XQEventFilterObject([=]
	(QEvent* ev)
		{
			XQDebug << "状态改变";
		}, QEvent::WindowActivate, receive));*/
}

QAction* XQSystemTray::menuAddCloseWindow(QMenu* menu, QWidget* receive, const QString& text)
{
	if (menu == nullptr)
		return nullptr;
	return menu->addAction(text, [=] {
		receive->close();
		});
}

QAction* XQSystemTray::menuAddQuit(QMenu* menu, const QString& text)
{
	if (menu == nullptr)
		return nullptr;
	return menu->addAction(text,qApp,&QApplication::quit);
}
